<template>
  <el-dialog title="编辑点位负责人" :visible.sync="show" :close-on-click-modal="false" :show-close="!disableAction" append-to-body width="800px" @closed="reset">
    <div style="margin: -10px 0 10px">
      <el-button size="mini" type="primary" icon="el-icon-plus" :disabled="disableAction" @click="openSelectUser()" v-if="showBtns.add">新增</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" size="small">
      <el-table-column label="负责人" prop="userNickName" show-overflow-tooltip min-width="100" />
      <el-table-column label="角色" align="center" show-overflow-tooltip min-width="100">
        <span slot-scope="{ row }">{{ row.roleIds | roleFilter(role2Name) }}</span>
      </el-table-column>
      <el-table-column label="更改人" prop="updatorName" show-overflow-tooltip width="100" />
      <el-table-column label="更改时间" prop="updateTime" width="150" />
      <el-table-column label="操作" width="200">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" :disabled="disableAction" @click="openSelectUser(row)" v-if="showBtns.edit">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :disabled="disableAction" @click="handleDelete(row)" v-if="showBtns.remove">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="showChangeRecord(row)" v-if="showBtns.info && row.spotBuilderId">变更记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer">
      <el-button type="primary" :disabled="disableAction" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="disableAction" @click="reset">取 消</el-button>
    </div>

    <SelectUser ref="SelectUser" title="选择责任人" :limit="userLimit" @selected="onSelectUser" />
    <ChangeRecord ref="ChangeRecord" />
  </el-dialog>
</template>
<script>
// 编辑点位负责人
import auth from '@/plugins/auth'
import { debounce } from '@/utils'
import { roleList } from '@/api/common'
import { getSpotBuilder, setSpotBuilder, verifyBuilder } from '@/api/cq/patrol'
import SelectUser from './SelectUser'
import ChangeRecord from './SpotBuilderChangeRecord'
const USER_LIMIT = 3 // 限制选择人数
export default {
  components: { SelectUser, ChangeRecord },
  filters: {
    roleFilter(val, role2Name = {}) {
      const str = val || ''
      return str
        .split(',')
        .map(i => role2Name[i])
        .filter(i => i)
        .join('，')
    }
  },
  data() {
    return {
      show: false,
      btnLoading: false,
      listLoading: false,
      list: [],
      queryParams: {
        projectId: '',
        isDelete: 0,
        patSpotId: ''
      },
      roleList: [],
      userLimit: USER_LIMIT,
      verifyLoading: false,
      currItem: {}
    }
  },
  computed: {
    disableAction() {
      return this.listLoading || this.verifyLoading
    },
    isEdit() {
      return !!this.queryParams.patSpotId
    },
    showBtns() {
      const permCode = 'cq:patrol:spot:builder'
      const spotPermCode = 'cq:patrol:spot'
      const edit = auth.hasPermi(`${permCode}:edit`)
      const add = auth.hasPermi(`${permCode}:add`)
      const remove = auth.hasPermi(`${permCode}:remove`)
      const info = auth.hasPermi(`${spotPermCode}:info`)
      return { edit, add, remove, info }
    },
    role2Name() {
      return this.roleList.reduce((o, i) => !void (o[i.fid] = i.roleName) && o, {})
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
  },
  methods: {
    reset() {
      this.show = false
      this.btnLoading = false
      this.listLoading = false
      this.list = []
      this.queryParams.projectId = ''
      this.queryParams.patSpotId = ''
      this.currItem = {}
    },
    open({ projectId, patSpotId, list } = {}) {
      if (!projectId) return this.msgError('参数错误，项目ID不能为空')

      this.queryParams.projectId = projectId
      this.queryParams.patSpotId = patSpotId || ''
      this.show = true

      if (!this.roleList.length) this.getRoleList()

      if (patSpotId) this.getList()
      else this.list = list || []
    },
    async getRoleList() {
      const res = await roleList().catch(() => false)
      if (res === false) return (this.roleList = [])
      this.roleList = res.data || []
    },
    async getList() {
      this.listLoading = true
      const res = await getSpotBuilder(this.queryParams).catch(() => false)
      this.listLoading = false
      if (res === false) return
      this.list = res.data || []
    },
    async handleDelete(item) {
      if (this.list.length === 1) return this.msgInfo('需保留至少一个负责人')
      const res1 = await this.$confirm(`确认删除：${item.userNickName}？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      // 验证是否可删
      if (item.spotBuilderId) {
        const opt = {
          spotBuilderId: item.spotBuilderId,
          userId: item.userId
        }
        const h = this.$createElement
        const loading = this.$message({ type: '', duration: 0, message: h('p', null, [h('i', { class: 'el-icon-loading' }), h('span', null, ' 验证用户状态')]) })
        this.verifyLoading = true
        const res = await verifyBuilder(opt).catch(() => false)
        this.verifyLoading = false
        loading.close()
        if (res === false) return
      }

      this.list = this.list.filter(i => i.userId !== item.userId)
    },
    openSelectUser(item = {}) {
      const len = this.list.length
      if (!item.userId && len >= USER_LIMIT) return this.msgInfo(`最多 ${USER_LIMIT} 个负责人`)

      this.currItem = item
      this.userLimit = item.userId ? 1 : USER_LIMIT - len
      this.$refs.SelectUser.open({ projectId: this.queryParams.projectId })
    },
    async onSelectUser(selected) {
      if (!selected?.length) return

      const item = this.currItem
      const { list } = this
      const { patSpotId } = this.queryParams

      const idMap = list.reduce((o, i) => !void (o[i.userId] = 1) && o, {})
      selected = selected
        .filter(i => !idMap[i.fid])
        .map(i => ({
          patSpotId,
          userId: i.fid,
          userNickName: i.nickName,
          roleIds: i.roleIds
        }))
      if (!selected.length) return this.msgInfo('已存在该负责人')

      // 新增用户
      if (!item.userId) return (this.list = list.concat(selected))

      // 更改用户
      const user = selected[0]
      item.userId = user.userId
      item.userNickName = user.userNickName
      item.roleIds = user.roleIds
    },
    showChangeRecord(item) {
      this.$refs.ChangeRecord.open({ patSpotId: item.patSpotId, spotBuilderId: item.spotBuilderId })
    },
    async onSubmit() {
      if (!this.isEdit) {
        this.show = false
        this.$emit('ok', this.list)
        return
      }

      const opt = {
        patSpotId: this.queryParams.patSpotId,
        cqPatrolSpotBuilders: this.list
      }
      this.btnLoading = true
      const res = await setSpotBuilder(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.msgSuccess('提交成功')
      this.show = false
      this.$emit('ok', this.list)
    }
  }
}
</script>
